<script setup>
import Table from '@/components/admin/Table.vue'
import Dialog from '@/components/admin/EditDialog.vue'
import {Delete, Download, Plus, ZoomIn, Search} from '@element-plus/icons-vue'
import {ref, reactive, onMounted, nextTick} from 'vue'
import {
  GetCustomMessageService,
  deleteCustomNoticeUrlsService,
  deleteCustomNoticeUrlService,
  addCustomService,
  beforeaddCustomService,
  editCustomMessageService
} from '@/api/custommessage.js'
import {ElMessage, ElLoading} from "element-plus";
// 绑定表格的内容(选项selection)
const multipleTableRef = ref()

// 表格相关数据
const customMsg = ref({
  columns: [
    {
      label: '序号',
      prop: 'id',
      width: '70'
    },
    {
      label: '姓名',
      prop: 'ownername',
      width: '250'
    },
    {
      label: '性别',
      prop: 'ownersex',
      width: '250',
      formatter: (row) => {
        switch (row.ownersex) {
          case 1: {
            return '男'
          }
          case 2: {
            return '女'
          }
        }
      }
    },
    {
      label: '手机号',
      prop: 'ownerphone',
      width: '250'
    },
    {
      label: '地址',
      prop: 'owneraddress',
      width: '400'
    },
    {
      label: '建档时间',
      prop: 'created_time',
      width: '200'
    },
    {
      label: '所属宠物',
      prop: 'pet',
      width: '150'
    }
  ],
  data: [],
  loading: true
})

// 获取所有的数据
const getList = () => {
  GetCustomMessageService(all.page, all.limit, all.keyword)
      .then((res) => {
        customMsg.value.data = res.data.results.data
        // 获取数据总数
        all.total = res.data.count
        customMsg.value.loading = false
        // console.log(res.data.results.data)
      })
      .catch((err) => {
        console.log(err)
      })
}
onMounted(() => {
  getList()
})
// 分页
const all = reactive({
  // 总数
  total: 0,
  // 页
  page: 1,
  // 条
  limit: 10,
  // 关键字
  keyword: ''
})

const sizeChange = (val) => {
  all.limit = val;
  getList()
};
/**
 * 页
 * val -- 当前条
 */
const currentChange = (val) => {
  all.page = val;
  getList()
};

// 全选
const multipleSelection = ref([]);
const selectionchange = (val) => {
  multipleSelection.value = val
  console.log(multipleSelection.value)
}
// 单个删除组件
const handleDelete = (row) => {
  const params = row.id;
  deleteCustomNoticeUrlService(params).then((res) => {
    console.log(res.data);
    getList()
  });
}
// 批量选择并删除
const handleDeleteArray = () => {
  if (multipleSelection.value.length <= 0) {
    ElMessage.warning('麻烦你选中了再点')
  }
  for (var i = 0; i < multipleSelection.value.length; i++) {
    const params = multipleSelection.value[i].id;
    const Ids = []
    Ids.push(...multipleSelection.value.map(row => row.id))
    console.log(Ids);
    deleteCustomNoticeUrlsService({Ids: Ids})
        .then((res) => {
          multipleSelection.value = []
          console.log(res.data);
          getList()
        });
  }
}
// 全选
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      console.log('multipleSelection.value', multipleTableRef)
      multipleTableRef.value.multipleTableRef.toggleRowSelection(row, undefined);
    });
  } else {
    multipleTableRef.value.multipleTableRef.clearSelection();
  }
}
// 对话框展开
const dialogObject = reactive({
  dialogVisible: false,
  title: '',
  width: '700',
  successBtnText: '确定',
  closeBtnText: '取消',
  isFooter: true
})
// 打开对话框组件时需要传入的标题
const addClick = () => {
  dialogObject.dialogVisible = true
  dialogObject.title = '建档'
}
// 表单
const formfields = ref({
  base: [
    {
      label: '姓名', field: 'customname',
      rules: [
        {required: true, message: '姓名需要填写', trigger: 'blur'}
      ]
    },
    {
      label: '性别', field: 'customsex', type: 'select',
      options: {
        data: [{label: '男', value: 1}, {label: '女', value: 2}]
      },
      rules: [{required: true, message: '性别需要选择'}]
    },
    {
      label: '手机号', field: 'customphone',
      rules: [
        {required: true, message: '手机号需要填写', trigger: 'blur'},
        {min: 3, max: 11, message: '手机号必须3-11位数字', trigger: 'blur'}
      ]
    },
    {
      label: '家庭住址', field: 'customaddress', rules: [{required: true, message: '家庭住址需要填写', trigger: 'blur'}]
    },
    {
      label: '所属宠物名', field: 'custompet'
    },
    {
      label: '建档时间', field: 'created_time', type: 'date', rules: [{required: true, message: '请选择日期', trigger: 'blur'}]
    }
  ],
})

const form = ref({
  customname: '',
  customsex: '',
  customphone: '',
  customaddress: '',
  custompet: '',
  created_time: ''
})

// 提交前先检验是否有这个宠物的名字
const checkPet = async () => {
  console.log(form.value.custompet)
  await beforeaddCustomService(form.value.custompet)
      .then((res) => {
        console.log(res)
      })
      .catch((error) => {
        console.log(error)
      })
}

// 提交表单增加数据
const handleFormSubmit = async (form) => {
  await addCustomService(form)
      .then((res) => {
        // console.log(res)
        dialogObject.dialogVisible = false
        getList()
      })
      .catch((error) => {
        console.log(error)
      })
}

// 单个数据的编辑
const handleEdit = (index, row) => {
  dialogObject.dialogVisible = true
  dialogObject.title = '人员信息改档'
  // console.log(row)
  nextTick(() => {
    form.value.customname = row.ownername
    form.value.customsex = row.ownersex
    form.value.customphone = row.ownerphone
    form.value.customaddress = row.owneraddress
    form.value.custompet = row.pet
    form.value.created_time = row.created_time
    form.value.id = row.id
  })
  console.log(form)
}

// 编辑表单提交
const handleFormEdit = async (form) => {
  console.log('form', form.customname)
  const data = {
    ownername: form.customname,
    ownersex: form.customsex,
    ownerphone: form.customphone,
    owneraddress: form.customaddress,
    pet: form.custompet,
    created_time: form.created_time,
    id: form.id
  }
  await editCustomMessageService(data)
      .then((res) => {
        console.log(res)
        dialogObject.dialogVisible = false
        getList()
      })
      .catch((error) => {
        console.log(error)
      })
}
//搜索框
const handleChange = () => {
  customMsg.value.loading = true
  setTimeout(() => {
    getList()
  }, 1000)
  console.log('找到了吗', res)
}

</script>

<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button type="success" @click="addClick">添加</el-button>
        <el-button type="danger" @click="handleDeleteArray">批量删除</el-button>
        <el-button type="primary" @click="toggleSelection(customMsg.data)">全选</el-button>
        <el-input
            v-model="all.keyword"
            class="searchInput"
            placeholder="手机号"
            :prefix-icon="Search"
            @change="handleChange"
        />
        <el-button :icon="Search" @click="handleChange"/>
      </div>
    </template>
    <Table
        ref="multipleTableRef"
        :customdata="customMsg"
        :all="all"
        @handleSizeChange="sizeChange"
        @handleCurrentChange="currentChange"
        @handleSelectionChange="selectionchange"
    >
      <template #operate>
        <el-table-column label="操作" width="180" show-overflow-tooltip>
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
            <el-popconfirm title="是否确定要删除吗" confirm-button-text="是" cancel-button-text="否"
                           @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button
                    size="small"
                    type="danger"
                >删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </template>
    </Table>
    <Dialog
        :dialogobject="dialogObject"
        :formlist="formfields.base"
        :model="form"
        @submit="handleFormSubmit"
        @edit="handleFormEdit"
    >
      <template #checkpet>
        <el-button type="primary" @click="checkPet">查询</el-button>
      </template>
    </Dialog>
  </el-card>

</template>

<style scoped>
.searchInput {
  width: 350px;
  height: 33px;
  margin-left: 20px;
}
</style>